package com.liaoye.demo_02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int tickets = 100;

    //采用jdk5以上的Lock对象来解决同步的问题
    private final Lock lock = new ReentrantLock();

    //注意多线程的锁对象得是同一个
    private Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            /*try {
                lock.lock();
                if(tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售" + (tickets--) + "张票");
                }
            } finally {
                lock.unlock();
            }*/
            synchronized (obj) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售" + (tickets--) + "张票");
                }
            }

        }
    }
}
